<template>
  <div class="app-container">
    <el-form :model="questionForm" :rules="rules" ref="questionFormRef" label-width="100px">
      <!-- 所属章节选择 -->
      <el-form-item label="所属章节" prop="chapterId" required>
        <el-tree-select
          v-model="questionForm.chapterId"
          :data="chapterOptions"
          :props="{ value: 'chapterId', label: 'chapterName', children: 'children' }"
          value-key="chapterId"
          placeholder="请选择所属章节"
          check-strictly
        />
      </el-form-item>
      
      <!-- 题干 -->
      <el-form-item label="题干" prop="questionContent" required>
        <div class="content-box" @click="openEditor('questionContent')">
          <div v-if="questionForm.questionContent" v-html="questionForm.questionContent" class="content-html"></div>
          <div v-else class="placeholder-text">点击编辑题干内容</div>
        </div>
      </el-form-item>
      
      <!-- 选项 -->
      <el-form-item label="选项" prop="options" required>
        <div v-for="(option, index) in questionForm.options" :key="index" class="question-option-item">
          <div class="option-label">{{ optionLabels[index] }}</div>
          <div class="content-box option-content" @click="openEditor('option', index)">
            <div v-if="option.optionContent" v-html="option.optionContent" class="content-html"></div>
            <div v-else class="placeholder-text">点击编辑选项内容</div>
          </div>
          <el-button
            type="danger"
            icon="Delete"
            circle
            @click="removeOption(index)"
            v-if="questionForm.options.length > 3"
          />
        </div>
      </el-form-item>
      
      <!-- 标准答案 -->
      <el-form-item label="标准答案" prop="answer" required>
        <el-checkbox-group v-model="questionForm.answer">
          <el-checkbox
            v-for="(option, index) in questionForm.options"
            :key="index"
            :label="optionLabels[index]"
          >
            {{ optionLabels[index] }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <!-- 分值 -->
      <el-form-item label="分值" prop="score" required>
        <el-input-number
          v-model="questionForm.score"
          :min="0.5"
          :max="20"
          :step="0.5"
          step-strictly
        />
      </el-form-item>
      
      <!-- 难度 -->
      <el-form-item label="难度" prop="difficulty" required>
        <el-rate
          v-model="questionForm.difficulty"
          :max="5"
          :texts="['简单', '较简单', '中等', '较难', '困难']"
          show-text
        />
      </el-form-item>

      <!-- 状态（仅编辑模式显示） -->
      <el-form-item label="状态" prop="status" v-if="isEdit">
        <el-radio-group v-model="questionForm.status">
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 解析 -->
      <el-form-item label="解析" prop="analysis">
        <div class="content-box" @click="openEditor('analysis')">
          <div v-if="questionForm.analysis" v-html="questionForm.analysis" class="content-html"></div>
          <div v-else class="placeholder-text">点击编辑解析内容</div>
        </div>
      </el-form-item>
      
      <!-- 底部按钮 -->
      <el-form-item class="button-group">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button 
          type="success" 
          icon="Plus" 
          @click="addOption" 
          v-if="questionForm.options.length < 9"
        >添加选项</el-button>
        <el-button 
          type="info" 
          icon="View" 
          @click="previewQuestion"
        >预览</el-button>
        <el-button 
          type="warning" 
          icon="ChatDotRound" 
          @click="openAIAssistant"
        >AI辅助</el-button>
      </el-form-item>
    </el-form>

    <!-- 富文本编辑器对话框 -->
    <el-dialog
      v-model="editorVisible"
      title="内容编辑"
      width="800px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="editor-container">
        <QuillEditor
          v-model:content="tempContent"
          content-type="html"
          theme="snow"
          toolbar="full"
          :options="editorOptions"
          ref="quillEditor"
        />
        <div class="image-tip">
          <p>提示：使用 $...$ 插入行内公式，使用 $$...$$ 插入块级公式</p>
          <p>提示：图片会自动限制大小，过大的图片将被等比例缩放</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmEdit">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="题目预览"
      width="600px"
      append-to-body
      @opened="renderMathInPreview" 
    >
      <div class="preview-container" ref="previewContainer">
        <div class="preview-title">题干:</div>
        <div class="preview-content content-html" v-html="processedQuestionContent"></div>
        
        <div class="preview-title">选项:</div>
        <div v-for="(option, index) in processedOptions" :key="index" class="preview-option">
          <span class="option-label">{{ optionLabels[index] }}.</span>
          <div class="preview-option-content content-html" v-html="option.optionContent"></div>
        </div>
        
        <div class="preview-title">标准答案:</div>
        <div class="preview-answer">{{ sortedPreviewAnswer }}</div>
        
        <div v-if="questionForm.analysis" class="preview-title">解析:</div>
        <div v-if="questionForm.analysis" class="preview-content content-html" v-html="processedAnalysis"></div>
      </div>
    </el-dialog>

    <!-- AI辅助对话框 -->
    <el-dialog
      v-model="aiDialogVisible"
      title="AI辅助出题"
      width="800px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      @close="handleAIDialogClose"
    >
      <div class="ai-container">
        <div class="ai-content" ref="aiContentRef">
          <div v-if="aiMessages.length === 0" class="ai-empty-message">
            <p>欢迎使用AI辅助出题功能！</p>
            <p>您可以：</p>
            <ul>
              <li>生成一道关于当前章节的多选题</li>
              <li>修改/完善当前编辑的题目</li>
              <li>针对特定知识点提问</li>
            </ul>
          </div>
          <div v-else class="ai-messages">
            <div v-for="(msg, idx) in aiMessages" :key="idx" :class="['ai-message', msg.role]">
              <div class="ai-message-content" v-html="msg.content"></div>
            </div>
          </div>
        </div>
        <div class="ai-input-area">
          <el-input
            v-model="aiPrompt"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题或需求..."
            @keydown.enter.ctrl.prevent="sendAIMessage"
          ></el-input>
        </div>
        <div class="ai-function-buttons">
          <el-tooltip content="直接生成题目" placement="top">
            <el-button type="primary" @click="generateQuestionWithAI" :loading="aiLoading">生成题目</el-button>
          </el-tooltip>
          <el-tooltip content="仅编辑已有题目时可用" placement="top">
            <el-button type="success" @click="optimizeQuestionWithAI" :loading="aiLoading" :disabled="!canOptimizeQuestion">优化题目</el-button>
          </el-tooltip>
          <el-tooltip content="分析当前题目" placement="top">
            <el-button type="info" @click="analyzeCurrentQuestion" :loading="aiLoading" :disabled="!isValidQuestion">分析题目</el-button>
          </el-tooltip>
          <el-tooltip content="获取改进建议" placement="top">
            <el-button type="warning" @click="getImprovementSuggestion" :loading="aiLoading" :disabled="!questionForm.questionId">改进建议</el-button>
          </el-tooltip>
          <el-tooltip content="测试AI API" placement="top">
            <el-button type="danger" @click="testAIApi" :loading="aiLoading">测试API</el-button>
          </el-tooltip>
        </div>
        <div class="ai-action-buttons">
          <el-button @click="sendAIMessage" :loading="aiLoading">发送</el-button>
          <el-button type="warning" @click="applyAIGeneratedContent" :disabled="!isContentApplicable">应用</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { listChapter } from '@/api/manage/chapter';
import { addQuestion, getQuestion, updateQuestion } from '@/api/manage/question';
import { 
  generateQuestion, 
  optimizeQuestion, 
  chatWithAI, 
  analyzeGeneratedQuestion, 
  generateQuestionSuggestion,
  testAIConnection
} from '@/api/manage/ai';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';

const route = useRoute();
const router = useRouter();
const isEdit = ref(false);

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
};

// 表单数据
const questionForm = ref({
  questionId: '',
  questionType: 1,
  questionContent: '',
  chapterId: null,
  difficulty: 3,
  answer: [],
  score: 2,
  analysis: '',
  status: 0,
  options: [
    { optionId: generateId(), optionLabel: 'A', optionContent: '' },
    { optionId: generateId(), optionLabel: 'B', optionContent: '' },
    { optionId: generateId(), optionLabel: 'C', optionContent: '' }
  ]
});

// 章节数据
const chapterOptions = ref([]);
// 选项标签
const optionLabels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];

// 表单校验规则
const rules = {
  chapterId: [{ required: true, message: '请选择所属章节', trigger: 'change' }],
  questionContent: [{ required: true, message: '请输入题干内容', trigger: 'blur' }],
  answer: [{ 
    required: true, 
    message: '多选题请至少选择2个正确答案', 
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请选择正确答案'));
      } else if (value.length < 2) {
        callback(new Error('多选题至少需要2个正确答案'));
      } else {
        callback();
      }
    }
  }],
  score: [{ required: true, message: '请设置分值', trigger: 'blur' }],
  difficulty: [{ required: true, message: '请设置难度', trigger: 'change' }]
};

const questionFormRef = ref(null);
const quillEditor = ref(null);

// 编辑器相关
const editorVisible = ref(false);
const tempContent = ref('');
const currentEditField = ref('');
const currentEditIndex = ref(-1);
const previewVisible = ref(false);

// 处理图片大小
const processImageSize = (html) => {
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  const images = tempDiv.querySelectorAll('img');
  images.forEach(img => {
    img.style.maxWidth = '100%';
    img.style.height = 'auto';
    img.style.objectFit = 'contain';
  });
  return tempDiv.innerHTML;
};

// Quill编辑器配置
const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'script': 'sub' }, { 'script': 'super' }],
      [{ 'indent': '-1' }, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image']
    ],
    imageUploader: {
      upload: file => {
        return new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append('file', file);
          
          fetch('/dev-api/common/upload', {
            method: 'POST',
            body: formData
          })
            .then(response => response.json())
            .then(result => {
              if (result.code === 200 && result.data) {
                resolve(result.data.url);
              } else {
                reject('上传失败: ' + (result.msg || '未知错误'));
              }
            })
            .catch(error => {
              reject('上传出错: ' + error.message);
            });
        });
      }
    }
  },
  placeholder: '请输入内容...'
};

// 获取章节树
const getChapterTreeselect = () => {
  listChapter().then(response => {
    const data = { chapterId: 0, chapterName: '离散数学', children: [] };
    data.children = handleTree(response.data, "chapterId", "parentId");
    chapterOptions.value = [data];
  });
};

// 处理树形结构
const handleTree = (data, id, parentId) => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (const d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (const d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
};

// 编辑器相关方法
const openEditor = (field, index = -1) => {
  currentEditField.value = field;
  currentEditIndex.value = index;
  tempContent.value = '';
  
  nextTick(() => {
    if (field === 'questionContent') {
      tempContent.value = questionForm.value.questionContent || '';
    } else if (field === 'analysis') {
      tempContent.value = questionForm.value.analysis || '';
    } else if (field === 'option' && index >= 0) {
      tempContent.value = questionForm.value.options[index].optionContent || '';
    }
    
    editorVisible.value = true;
    
    nextTick(() => {
      if (quillEditor.value) {
        quillEditor.value.focus();
      }
    });
  });
};

const confirmEdit = () => {
  const processedContent = processImageSize(tempContent.value);
  
  if (currentEditField.value === 'questionContent') {
    questionForm.value.questionContent = processedContent;
  } else if (currentEditField.value === 'analysis') {
    questionForm.value.analysis = processedContent;
  } else if (currentEditField.value === 'option' && currentEditIndex.value >= 0) {
    questionForm.value.options[currentEditIndex.value].optionContent = processedContent;
  }
  
  editorVisible.value = false;
};

const cancelEdit = () => {
  editorVisible.value = false;
  tempContent.value = '';
};

// 添加选项
const addOption = () => {
  if (questionForm.value.options.length < 9) {
    const nextIndex = questionForm.value.options.length;
    questionForm.value.options.push({
      optionId: generateId(),
      optionLabel: optionLabels[nextIndex],
      optionContent: ''
    });
  } else {
    ElMessage.warning('最多只能添加9个选项');
  }
};

const removeOption = (index) => {
  if (questionForm.value.options.length > 2) {
    const removedLabel = optionLabels[index];
    const answerIndex = questionForm.value.answer.indexOf(removedLabel);
    if (answerIndex > -1) {
      questionForm.value.answer.splice(answerIndex, 1);
    }
    
    questionForm.value.options.splice(index, 1);
    
    for (let i = 0; i < questionForm.value.options.length; i++) {
      questionForm.value.options[i].optionLabel = optionLabels[i];
    }
  } else {
    ElMessage.warning('至少需要保留2个选项');
  }
};

// 添加一个排序多选题答案的方法
const sortMultiChoiceAnswer = (answerArray) => {
  if (!answerArray || answerArray.length === 0) return [];
  return [...answerArray].sort();
};

// 预览题目
const previewQuestion = () => {
  if (!questionForm.value.questionContent) {
    ElMessage.warning('请先填写题干内容');
    return;
  }
  
  // 确保至少有2个正确答案
  if (questionForm.value.answer.length < 2) {
    ElMessage.warning('多选题至少需要2个正确答案');
    return;
  }
  
  // 对标准答案进行排序，以便预览时显示升序排列的答案
  // 注意：在预览中只改变显示，不修改原始数据
  previewVisible.value = true;
};

// 表单操作
// 重置表单
const resetForm = () => {
  questionFormRef.value.resetFields();
  questionForm.value.options = [
    { optionId: generateId(), optionLabel: 'A', optionContent: '' },
    { optionId: generateId(), optionLabel: 'B', optionContent: '' },
    { optionId: generateId(), optionLabel: 'C', optionContent: '' }
  ];
  questionForm.value.answer = [];
};

// 为预览准备的标准答案（已排序）
const sortedPreviewAnswer = computed(() => {
  return sortMultiChoiceAnswer(questionForm.value.answer).join(',');
});

// 修改提交表单部分，确保答案以字母升序存储
const submitForm = () => {
  questionFormRef.value.validate(valid => {
    if (valid) {
      const emptyOption = questionForm.value.options.find(opt => !opt.optionContent.trim());
      if (emptyOption) {
        ElMessage.warning('请填写所有选项内容');
        return;
      }
      
      // 确保多选题至少有2个正确答案
      if (questionForm.value.answer.length < 2) {
        ElMessage.warning('多选题至少需要2个正确答案');
        return;
      }
      
      // 对答案进行排序
      const sortedAnswer = sortMultiChoiceAnswer(questionForm.value.answer);
      
      const submitData = {
        questionId: questionForm.value.questionId || generateId(),
        questionType: 1, // 多选题类型
        questionContent: questionForm.value.questionContent,
        chapterId: questionForm.value.chapterId,
        difficulty: questionForm.value.difficulty,
        answer: sortedAnswer.join(','), // 将排序后的答案数组转换为字符串
        score: questionForm.value.score,
        analysis: questionForm.value.analysis,
        status: questionForm.value.status,
        options: questionForm.value.options.map((opt, index) => ({
          optionId: opt.optionId || generateId(),
          optionLabel: optionLabels[index],
          optionContent: opt.optionContent,
          questionId: questionForm.value.questionId || ''
        }))
      };
      
      if (isEdit.value) {
        updateQuestion(submitData).then(response => {
          ElMessage.success('修改成功');
          router.push({ path: '/question/question' });
        });
      } else {
        submitData.status = 0;
        addQuestion(submitData).then(response => {
          ElMessage.success('保存成功');
          router.push({ path: '/question/question' });
        });
      }
    }
  });
};

// 获取题目详情
const getDetail = (questionId) => {
  getQuestion(questionId).then(response => {
    const questionData = response.data;
    questionForm.value = {
      ...questionData,
      answer: questionData.answer ? questionData.answer.split(',') : [], // 将字符串转换为数组
      options: questionData.options || []
    };
  });
};

// 修改MathJax加载方式
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      // 如果已经加载，重新配置并尝试渲染
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
    // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
    };
    document.head.appendChild(script);
  });
};

// 处理数学公式的函数
const processMathContent = (html) => {
  // 直接返回内容，由MathJax处理
  return html;
};

// 为预览准备的处理后内容
const processedQuestionContent = computed(() => {
  return processMathContent(questionForm.value.questionContent || '');
});

const processedOptions = computed(() => {
  return questionForm.value.options.map(option => ({
    ...option,
    optionContent: processMathContent(option.optionContent || '')
  }));
});

const processedAnalysis = computed(() => {
  return processMathContent(questionForm.value.analysis || '');
});

// 优化渲染函数，添加更多日志和重试机制
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    
    // 作为备选方案，使用KaTeX尝试渲染
    try {
      if (!window.katex) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.css';
        document.head.appendChild(link);
        
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.js';
        script.onload = () => {
          const autoRenderScript = document.createElement('script');
          autoRenderScript.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/contrib/auto-render.min.js';
          autoRenderScript.onload = () => {
            window.renderMathInElement(previewContainer.value, {
              delimiters: [
                {left: '$$', right: '$$', display: true},
                {left: '$', right: '$', display: false}
              ]
            });
          };
          document.head.appendChild(autoRenderScript);
        };
        document.head.appendChild(script);
      } else {
        window.renderMathInElement(previewContainer.value, {
          delimiters: [
            {left: '$$', right: '$$', display: true},
            {left: '$', right: '$', display: false}
          ]
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

// AI辅助对话框相关变量
const aiDialogVisible = ref(false);
const aiContentRef = ref(null);
const aiMessages = ref([]);
const aiPrompt = ref('');
const aiLoading = ref(false);
const aiGeneratedContent = ref(null);
// 跟踪AI最近操作类型，用于判断内容是否可应用
const aiLastAction = ref('');
const isContentApplicable = computed(() => {
  // 只有生成题目操作的内容可以应用
  return aiGeneratedContent.value !== null && aiLastAction.value === 'generate';
});
const isValidQuestion = computed(() => {
  return questionForm.value.questionContent.trim() !== '' && 
         questionForm.value.options.length >= 2 && 
         questionForm.value.answer.length > 0;
});

// 添加表示当前题目是否可优化的计算属性
const canOptimizeQuestion = computed(() => {
  return isEdit.value && 
         questionForm.value.questionId && 
         isValidQuestion.value;
});

// 添加getDifficultyText函数
const getDifficultyText = (level) => {
  const labels = ['简单', '较简单', '中等', '较难', '困难'];
  return labels[(level - 1) >= 0 && (level - 1) < labels.length ? (level - 1) : 2] || '中等';
};

// 打开AI辅助对话框
const openAIAssistant = () => {
  aiDialogVisible.value = true;
  // 初始化消息，如果为空的话
  if (aiMessages.value.length === 0) {
    aiMessages.value.push({
      role: 'assistant',
      content: '你好！我是AI助手，可以帮你创建或优化多选题。请告诉我你的需求。'
    });
  }
};

// 处理AI对话框关闭事件
const handleAIDialogClose = () => {
  // 清空生成内容和重置状态
  aiPrompt.value = '';
  aiGeneratedContent.value = null;
  aiLastAction.value = '';
  // 保留历史消息，但限制数量
  if (aiMessages.value.length > 10) {
    aiMessages.value = aiMessages.value.slice(-10);
  }
};

// 处理AI消息中的公式
const renderAIMessageMath = async () => {
  await nextTick();
  try {
    // 首先处理数字后跟逗号和下划线的格式
    const mathElements = document.querySelectorAll('.ai-message.assistant');
    if (mathElements.length > 0) {
      for (const el of mathElements) {
        // 替换所有数字后跟逗号和下划线的模式
        const originalHtml = el.innerHTML;
        const fixedHtml = originalHtml.replace(/(\d),(_+)/g, (match, digit, underscores) => {
          console.log(`AI消息中修复填空格式: 替换 "${match}" 为 "${underscores}"`);
          return underscores;
        });
        
        if (originalHtml !== fixedHtml) {
          el.innerHTML = fixedHtml;
        }
      }
    }
    
    // 尝试渲染消息中的公式
    if (window.MathJax && window.MathJax.typesetPromise) {
      if (mathElements.length > 0) {
        await window.MathJax.typesetPromise(mathElements);
        console.log('AI消息中的公式渲染完成');
      }
    }
  } catch (error) {
    console.error('AI消息公式渲染错误:', error);
  }
};

// 发送消息到AI
const sendAIMessage = async () => {
  if (!aiPrompt.value.trim()) {
    ElMessage.warning('请输入内容');
    return;
  }
  
  try {
    aiLoading.value = true;
    
    const message = aiPrompt.value.trim();
    aiMessages.value.push({ role: 'user', content: message });
    
    // 构建消息历史数组 - 只传递内容
    const messageHistory = aiMessages.value.slice(0, -1).map(msg => msg.content);
    
    console.log('发送AI消息:', {
      messageHistory: messageHistory.length,
      message
    });
    
    // 注意参数顺序：先是prompt，再是messages
    const response = await chatWithAI(message, messageHistory);
    
    if (response && response.data && response.data.content) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: response.data.content.replace(/\n/g, '<br>') 
      });
      
      // 标记最后操作类型为聊天
      aiLastAction.value = 'chat';
      
      // 聊天消息不会自动尝试解析题目结构
      aiGeneratedContent.value = null;
    } else {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: '抱歉，AI未能返回有效回复，请稍后再试。' 
      });
    }
    
    // 清空输入框
    aiPrompt.value = '';
  } catch (error) {
    console.error('发送AI消息出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，发送消息失败: ' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 从AI生成的文本中解析题目结构
const parseQuestionFromText = (text) => {
  // 初始化结果对象
  const questionData = {
    questionContent: '',
    options: [],
    answer: '',
    analysis: ''
  };
  
  try {
    console.log('开始解析多选题文本，总长度:', text.length);
    
    // 清理文本：移除可能干扰解析的内容
    text = text.replace(/```[a-z]*\n/g, '') // 移除代码块开始标记
           .replace(/```\s*$/g, '')       // 移除代码块结束标记
           .replace(/^\s*```\s*$/gm, '')  // 移除单独一行的代码块标记
           .replace(/\n*\*\*注意：\*\*.*$/s, '') // 移除注意提示
           .replace(/\n*Note:.*$/s, '');  // 移除英文注意提示
    
    // 使用规范化格式解析
    
    // 1. 提取题干
    const titleSectionMatch = text.match(/###\s*题干\s*\n+([\s\S]+?)(?=\n+###|$)/i);
    if (titleSectionMatch && titleSectionMatch[1] && titleSectionMatch[1].trim().length > 5) {
      questionData.questionContent = titleSectionMatch[1].trim();
      console.log('通过"### 题干"标记提取到题干，长度:', questionData.questionContent.length);
    }
    
    // 2. 提取选项
    const optionsSectionMatch = text.match(/###\s*选项\s*\n+([\s\S]+?)(?=\n+###|$)/i);
    if (optionsSectionMatch && optionsSectionMatch[1]) {
      const optionsContent = optionsSectionMatch[1].trim();
      console.log('找到选项部分，长度:', optionsContent.length);
      
      // 解析选项（A. xxx, B. xxx 格式）
      const optionRegex = /([A-F])[.．、:：]\s*([\s\S]+?)(?=\n+[A-F][.．、:：]|\n+###|$)/g;
      let optionMatch;
      
      while ((optionMatch = optionRegex.exec(optionsContent + '\n')) !== null) {
        const optionLabel = optionMatch[1].trim();
        const optionContent = optionMatch[2].trim();
        
        if (optionContent) {
          questionData.options.push({
            optionLabel,
            optionContent
          });
          console.log(`提取到选项${optionLabel}，内容长度:`, optionContent.length);
        }
      }
    }
    
    // 3. 提取答案
    const answerSectionMatch = text.match(/###\s*答案\s*\n+\s*([A-F,]+)\s*(?=\n+###|$)/i);
    if (answerSectionMatch && answerSectionMatch[1]) {
      questionData.answer = answerSectionMatch[1].trim().toUpperCase();
      console.log('提取到答案:', questionData.answer);
    } else {
      // 备用答案提取方法，尝试其他可能格式
      const answerPatterns = [
        /###\s*答案\s*\n+\s*选[择项]+\s*([A-F,]+)\s*(?=\n+###|$)/i,
        /###\s*答案\s*\n+\s*([A-F][,，][A-F](?:[,，][A-F])*)\s*(?=\n+###|$)/i,
        /正确(?:选项|答案)[为是:：]*\s*([A-F][,，][A-F](?:[,，][A-F])*)/i,
        /答案[为是:：]*\s*([A-F][,，][A-F](?:[,，][A-F])*)/i
      ];
      
      for (const pattern of answerPatterns) {
        const match = text.match(pattern);
        if (match && match[1]) {
          // 规范化答案格式，确保使用英文逗号且无空格
          questionData.answer = match[1].trim()
            .replace(/，/g, ',') // 将中文逗号替换为英文逗号
            .replace(/\s+/g, '') // 移除所有空格
            .toUpperCase();
          console.log('通过备用方法提取到答案:', questionData.answer);
          break;
        }
      }
    }
    
    // 4. 提取解析
    const analysisSectionMatch = text.match(/###\s*解析\s*\n+([\s\S]+?)(?=$)/i);
    if (analysisSectionMatch && analysisSectionMatch[1]) {
      questionData.analysis = analysisSectionMatch[1].trim();
      console.log('提取到解析，长度:', questionData.analysis.length);
    }
    
    // 验证解析结果并输出详细日志
    const isValid = questionData.questionContent.length > 0 && 
                   questionData.options.length > 0 && 
                   questionData.answer.length > 0 &&
                   questionData.answer.indexOf(',') !== -1; // 多选题答案必须包含逗号
    
    console.log('题目解析结果：', {
      有题干: questionData.questionContent.length > 0,
      题干长度: questionData.questionContent.length,
      选项数量: questionData.options.length,
      答案: questionData.answer,
      解析长度: questionData.analysis.length
    });
    
    // 按照选项标签排序选项
    if (questionData.options.length > 0) {
      questionData.options.sort((a, b) => a.optionLabel.localeCompare(b.optionLabel));
    }
    
    if (isValid) {
      console.log('题目解析成功');
      return questionData;
    } else {
      console.warn('题目解析不完整，请检查生成的内容格式');
      return null;
    }
  } catch (error) {
    console.error('解析题目时发生错误:', error);
    return null;
  }
};

// 应用AI生成的内容到表单
const applyAIGeneratedContent = () => {
  if (!aiGeneratedContent.value) {
    console.warn('没有可应用的AI生成内容');
    return;
  }
  
  try {
    console.log('准备应用AI生成内容:', aiGeneratedContent.value);
    
    // 从content中提取更完整的题目信息（如果有完整内容）
    if (aiGeneratedContent.value.content) {
      console.log('检测到完整content字段，尝试从中提取题目结构');
      const extractedData = parseQuestionFromText(aiGeneratedContent.value.content);
      if (extractedData && extractedData.questionContent && extractedData.questionContent.length > 10) {
        console.log('从完整content中成功提取题目数据，使用提取的结构');
        // 优先使用从content提取的完整数据
        aiGeneratedContent.value = {
          ...aiGeneratedContent.value,
          ...extractedData
        };
      }
    }
    
    // 输出处理前的各个部分内容
    console.log('应用前题目信息：', {
      题干: aiGeneratedContent.value.questionContent,
      选项数量: aiGeneratedContent.value.options?.length || 0,
      选项内容: aiGeneratedContent.value.options,
      答案: aiGeneratedContent.value.answer,
      解析: aiGeneratedContent.value.analysis?.substring(0, 50) + '...'
    });
    
    // 应用题干
    if (aiGeneratedContent.value.questionContent) {
      // 清理前导文本和标记
      let cleanedContent = aiGeneratedContent.value.questionContent
        .replace(/^以下是一道关于[^"]*的[^"]*题：/i, '')
        .replace(/^这是一道关于[^"]*的[^"]*题：/i, '')
        .replace(/^下面是一道[^"]*题：/i, '')
        .replace(/^这是一道[^"]*题：/i, '')
        .replace(/^###\s*题目\s*/i, '') // 移除"### 题目"标记
        .replace(/\s*###\s*选项\s*$/i, '') // 移除末尾的"### 选项"标记
        .trim();
        
      console.log('已应用题干内容，清理前导文本后:', cleanedContent);
      
      // 确保题干内容不为空并正确设置
      if (cleanedContent && cleanedContent.length > 10) {
        // 应用前进行最终清理，确保没有标记
        questionForm.value.questionContent = cleanedContent
          .replace(/^###\s*题目\s*/i, '')
          .replace(/^###\s*题干\s*/i, '')
          .replace(/\s*###\s*选项\s*$/i, '')
          .trim();
        console.log('成功设置题干内容，长度:', questionForm.value.questionContent.length);
        console.log('最终题干内容前50个字符:', questionForm.value.questionContent.substring(0, 50) + '...');
      } else if (aiGeneratedContent.value.content) {
        // 如果清理后的题干为空但有原始content，尝试提取### 题干或### 题目部分
        let titleMatch = aiGeneratedContent.value.content.match(/###\s*题干\s*\n+([\s\S]+?)(?=\n+###|$)/i);
        if (!titleMatch) {
          titleMatch = aiGeneratedContent.value.content.match(/###\s*题目\s*\n+([\s\S]+?)(?=\n+###|$)/i);
        }
        
        if (titleMatch && titleMatch[1] && titleMatch[1].trim().length > 10) {
          let extractedTitle = titleMatch[1].trim()
            .replace(/^以下是一道.+的多选题：\s*/i, '') // 移除引导语
            .replace(/^这是一道.+的多选题：\s*/i, '') // 移除引导语
            .replace(/^###\s*题目\s*/i, '') // 移除可能嵌套的标题标记
            .replace(/^###\s*题干\s*/i, '') // 移除可能嵌套的标题标记
            .replace(/\s*###\s*选项\s*$/i, '') // 移除可能的选项标记
            .trim();
          
          questionForm.value.questionContent = extractedTitle;
          console.log('从content中提取题干/题目部分作为题干，长度:', questionForm.value.questionContent.length);
          console.log('提取的题干内容前50个字符:', questionForm.value.questionContent.substring(0, 50) + '...');
        } else {
          console.warn('无法提取有效题干，使用原始内容');
          questionForm.value.questionContent = aiGeneratedContent.value.questionContent;
        }
      } else {
        console.warn('清理后的题干内容为空，使用原始内容');
        questionForm.value.questionContent = aiGeneratedContent.value.questionContent;
      }
    } else {
      console.warn('AI生成内容中没有题干');
    }
    
    // 应用选项
    if (aiGeneratedContent.value.options && aiGeneratedContent.value.options.length > 0) {
      const newOptions = aiGeneratedContent.value.options;
      console.log('应用选项，数量:', newOptions.length);
      
      // 确保选项数量足够
      while (questionForm.value.options.length < newOptions.length) {
        addOption();
      }
      
      // 应用选项内容
      newOptions.forEach((option, index) => {
        if (index < questionForm.value.options.length) {
          // 防止出现undefined
          const content = option.optionContent || '';
          // 去除选项内容可能存在的格式符号
          let cleanContent = content
            .replace(/^[A-I][.．、:：]\s*/i, '') // 移除选项标记
            .replace(/###\s*$/g, '') // 移除末尾的###标记
            .replace(/\s*X\s*$/i, '') // 移除末尾可能的X标记
            .trim();
            
          questionForm.value.options[index].optionContent = cleanContent;
          questionForm.value.options[index].optionLabel = option.optionLabel || String.fromCharCode(65 + index);
          
          // 输出每个选项处理后的内容
          console.log(`选项${option.optionLabel}处理后内容:`, cleanContent);
        }
      });
      
      console.log('选项应用完成，最终数量:', questionForm.value.options.length);
    } else {
      console.warn('AI生成内容中没有选项');
    }
    
    // 应用答案 - 多选题特有的处理方式
    let answerApplied = false;
    if (aiGeneratedContent.value.answer && Array.isArray(aiGeneratedContent.value.answer)) {
      console.log('应用多选题答案:', aiGeneratedContent.value.answer);
      
      // 处理答案数组，确保每个答案都是有效的选项标签
      let validAnswers = [];
      
      // 如果答案数组是字符串数组，处理每一项
      if (aiGeneratedContent.value.answer.length > 0) {
        validAnswers = aiGeneratedContent.value.answer
          .flatMap(ans => {
            // 处理可能的组合答案字符串如"A,B,C"或"A、B、C"
            if (typeof ans === 'string' && ans.length > 1 && /[,，、\s]/.test(ans)) {
              // 分割并返回所有字母
              return ans.split(/[,，、\s]+/).filter(a => /^[A-I]$/i.test(a));
            }
            return ans;
          })
          .map(ans => typeof ans === 'string' ? ans.trim().toUpperCase() : '')
          .filter(ans => /^[A-I]$/.test(ans) && optionLabels.includes(ans));
        
        // 去重
        validAnswers = Array.from(new Set(validAnswers));
      }
      
      if (validAnswers.length > 0) {
        // 确保至少有2个答案（多选题要求）
        if (validAnswers.length >= 2) {
          questionForm.value.answer = validAnswers;
          console.log('成功设置多选题答案:', validAnswers);
          answerApplied = true;
        } else {
          console.warn('答案数量不足2个，无法应用到多选题:', validAnswers);
        }
      } else {
        console.warn('无效的多选题答案格式:', aiGeneratedContent.value.answer);
      }
    }
    
    // 如果答案没有应用，但有content字段，尝试从content中提取多选题答案
    if (!answerApplied && aiGeneratedContent.value.content) {
      // 提取答案部分
      let answerMatch = aiGeneratedContent.value.content.match(/###\s*(?:答案|正确答案)[：:]\s*([^\n]+)/i);
      if (!answerMatch) {
        // 尝试其他可能的答案格式
        answerMatch = aiGeneratedContent.value.content.match(/正确(?:选项|答案)[是为：:]\s*([^\n]+)/i);
      }
      
      if (answerMatch && answerMatch[1]) {
        const answerText = answerMatch[1].trim();
        console.log('从content中提取到原始答案文本:', answerText);
        
        // 提取所有A-I格式的答案字母
        const letterMatches = answerText.match(/[A-I]/gi);
        if (letterMatches) {
          // 去重并转大写
          const uniqueAnswers = Array.from(new Set(letterMatches)).map(a => a.toUpperCase())
            .filter(a => optionLabels.includes(a));
          
          // 确保至少有2个答案（多选题要求）
          if (uniqueAnswers.length >= 2) {
            questionForm.value.answer = uniqueAnswers;
            console.log('从content中提取并设置多选题答案:', uniqueAnswers);
            answerApplied = true;
          } else {
            console.warn('从content中提取的答案数量不足2个，无法应用到多选题:', uniqueAnswers);
          }
        }
      }
      
      // 如果仍然没有找到答案，尝试查找"正确"选项描述
      if (!answerApplied) {
        // 在整个内容中搜索选项描述
        const correctOptions = [];
        const lines = aiGeneratedContent.value.content.split('\n');
        
        for (const line of lines) {
          if (/正确|对|true|选择/i.test(line) && /[A-I]/i.test(line)) {
            const letterMatches = line.match(/[A-I]/gi);
            if (letterMatches) {
              letterMatches.forEach(letter => {
                if (optionLabels.includes(letter.toUpperCase())) {
                  correctOptions.push(letter.toUpperCase());
                }
              });
            }
          }
        }
        
        // 移除重复项
        const uniqueCorrectOptions = Array.from(new Set(correctOptions));
        
        // 确保至少有2个答案（多选题要求）
        if (uniqueCorrectOptions.length >= 2) {
          questionForm.value.answer = uniqueCorrectOptions;
          console.log('从内容描述中提取并设置多选题答案:', uniqueCorrectOptions);
          answerApplied = true;
        }
      }
    }
    
    // 如果全都失败了但有选项，创建两个默认正确答案
    if (!answerApplied && questionForm.value.options.length >= 2) {
      console.warn('无法从AI内容中提取有效答案，设置默认答案');
      questionForm.value.answer = [questionForm.value.options[0].optionLabel, questionForm.value.options[1].optionLabel];
      console.log('设置默认多选题答案:', questionForm.value.answer);
      answerApplied = true;
      
      // 显示提示信息
      ElMessage.warning('未能提取有效答案，已设置默认答案A和B，请手动检查并修改');
    }
    
    // 应用解析
    let analysisApplied = false;
    if (aiGeneratedContent.value.analysis && aiGeneratedContent.value.analysis.length > 5) {
      const analysis = aiGeneratedContent.value.analysis;
      console.log('应用解析，长度:', analysis.length);
      questionForm.value.analysis = analysis;
      console.log('成功设置解析内容');
      analysisApplied = true;
    }
    
    // 如果解析没有应用，但有content字段，尝试从content中提取
    if (!analysisApplied && aiGeneratedContent.value.content) {
      const analysisMatch = aiGeneratedContent.value.content.match(/###\s*(?:解析|分析|解答)\s*\n+([\s\S]+?)(?=$)/i);
      if (analysisMatch && analysisMatch[1] && analysisMatch[1].trim().length > 5) {
        questionForm.value.analysis = analysisMatch[1].trim();
        console.log('从content中提取并设置解析，长度:', questionForm.value.analysis.length);
        analysisApplied = true;
      }
    }
    
    if (!analysisApplied) {
      console.warn('AI生成内容中没有解析');
    }
    
    // 最终应用结果输出
    console.log('题目最终应用结果：', {
      题干: questionForm.value.questionContent,
      选项: questionForm.value.options.map(opt => `${opt.optionLabel}: ${opt.optionContent.substring(0, 30)}...`),
      答案: questionForm.value.answer,
      解析: questionForm.value.analysis?.substring(0, 50) + '...'
    });
    
    // 应用成功后给用户提示
    ElMessage.success('已成功应用AI生成的内容');
  } catch (error) {
    console.error('应用AI生成内容出错:', error);
    ElMessage.error('应用AI生成内容时出错: ' + (error.message || '未知错误'));
  }
};

// 通过AI生成题目
const generateQuestionWithAI = async () => {
  try {
    aiLoading.value = true;
    aiPrompt.value = '';
    const promptText = `请帮我创建一道关于${questionForm.value.chapterId ? chapterOptions.value[0].children.find(c => c.chapterId === questionForm.value.chapterId)?.chapterName || '离散数学' : '离散数学'}的${getDifficultyText(questionForm.value.difficulty)}的多选题，请提供完整的题干、选项、答案和解析。`;
    
    aiMessages.value.push({ role: 'user', content: promptText });
    
    // 使用当前表单中的选项数量，而不是固定值
    const optionCount = questionForm.value.options.length;
    
    const response = await generateQuestion(
      questionForm.value.chapterId || '', 
      1, // 多选题
      questionForm.value.difficulty, 
      promptText,
      optionCount // 使用动态选项数量
    );
    
    console.log('AI生成题目响应:', response);
    
    if (response && response.data) {
      const content = response.data.content;
      if (content) {
        aiMessages.value.push({ 
          role: 'assistant', 
          content: content.replace(/\n/g, '<br>') 
        });
        
        // 标记最后操作类型为生成
        aiLastAction.value = 'generate';
        
        // 创建结构化题目数据对象
        let structuredQuestionData = {
          content: content // 保留原始完整内容
        };
        
        // 如果后端已经解析了题目结构
        if (response.data.questionContent) {
          // 清理后端返回的题干内容，移除不需要的前缀和标记
          let cleanedQuestionContent = response.data.questionContent
            .replace(/^以下是一道关于[^"]*的[^"]*题：\s*/i, '')
            .replace(/^这是一道关于[^"]*的[^"]*题：\s*/i, '')
            .replace(/^###\s*题目\s*/i, '') // 移除"### 题目"标记
            .replace(/\s*###\s*选项\s*$/i, '') // 移除末尾的"### 选项"标记
            .trim();
          
          // 如果清理后内容有效，则使用；否则尝试从content中提取
          if (cleanedQuestionContent && cleanedQuestionContent.length > 10) {
            structuredQuestionData.questionContent = cleanedQuestionContent;
          } else if (content) {
            // 尝试直接从content提取题干部分
            let titleMatch = content.match(/###\s*题干\s*\n+([\s\S]+?)(?=\n+###|$)/i);
            if (!titleMatch) {
              titleMatch = content.match(/###\s*题目\s*\n+([\s\S]+?)(?=\n+###|$)/i);
            }
            
            if (titleMatch && titleMatch[1] && titleMatch[1].trim().length > 10) {
              let extractedTitle = titleMatch[1].trim()
                .replace(/^以下是一道.+的多选题：\s*/i, '') // 移除引导语
                .replace(/^这是一道.+的多选题：\s*/i, '') // 移除引导语
                .trim();
              
              structuredQuestionData.questionContent = extractedTitle;
              console.log('从content中直接提取题干/题目部分，长度:', structuredQuestionData.questionContent.length);
            } else {
              structuredQuestionData.questionContent = response.data.questionContent;
            }
          } else {
            structuredQuestionData.questionContent = response.data.questionContent;
          }
          
          // 处理选项 - 确保不丢失内容
          if (response.data.options && response.data.options.length > 0) {
            const cleanOptions = response.data.options.map(opt => ({
              optionLabel: opt.optionLabel,
              optionContent: opt.optionContent
                .replace(/\n\n\n###$/, '')
                .replace(/\s*###.*$/gm, '')
                .replace(/\n{2,}/g, '\n')
                .replace(/\s*X\s*$/i, '') // 移除末尾可能的X标记
                .trim()
            }));
            structuredQuestionData.options = cleanOptions;
          }
          
          // 添加答案和解析 - 多选题答案是数组
          if (response.data.answer) {
            // 确保答案是数组格式
            if (typeof response.data.answer === 'string') {
              structuredQuestionData.answer = response.data.answer.split(',');
            } else {
              structuredQuestionData.answer = response.data.answer;
            }
          }
          
          if (response.data.analysis) {
            structuredQuestionData.analysis = response.data.analysis;
          }
          
          // 输出后端解析的结构化数据
          console.log('使用后端解析的结构化数据:', structuredQuestionData);
        }
        
        // 如果后端没有提供结构化数据或结构不完整，前端尝试解析
        if (!structuredQuestionData.questionContent || 
            !structuredQuestionData.options || 
            !structuredQuestionData.answer || structuredQuestionData.answer.length === 0) {
            
          // 使用增强的解析函数从完整内容中提取结构
          const parsedData = parseQuestionFromText(content);
          if (parsedData) {
            // 补充缺失的字段
            if (!structuredQuestionData.questionContent && parsedData.questionContent) {
              structuredQuestionData.questionContent = parsedData.questionContent;
            }
            
            if ((!structuredQuestionData.options || structuredQuestionData.options.length === 0) && 
                parsedData.options && parsedData.options.length > 0) {
              structuredQuestionData.options = parsedData.options;
            }
            
            if ((!structuredQuestionData.answer || structuredQuestionData.answer.length === 0) && 
                parsedData.answer && parsedData.answer.length > 0) {
              structuredQuestionData.answer = parsedData.answer;
            }
            
            if (!structuredQuestionData.analysis && parsedData.analysis) {
              structuredQuestionData.analysis = parsedData.analysis;
            }
            
            console.log('前端解析后补充的题目数据:', parsedData);
          }
        }
        
        // 保存生成的内容
        aiGeneratedContent.value = structuredQuestionData;
        console.log('最终处理后的题目数据:', structuredQuestionData);
        
        // 提示用户可以应用内容
        ElMessage.success('AI已生成题目，可点击"应用"按钮应用到表单');
      } else {
        console.warn('AI返回数据中缺少content字段');
        aiMessages.value.push({ 
          role: 'assistant', 
          content: '生成题目返回了不完整的数据，请重试。' 
        });
      }
    } else {
      console.warn('AI返回数据格式不正确:', response);
      aiMessages.value.push({ 
        role: 'assistant', 
        content: '生成题目返回了无效数据，请重试。' 
      });
    }
  } catch (error) {
    console.error('AI生成题目出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，生成题目失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 优化现有题目
const optimizeQuestionWithAI = async () => {
  try {
    // 检查是否有有效题目ID（即只能在编辑模式使用）
    if (!isEdit.value || !questionForm.value.questionId) {
      ElMessage.warning('优化题目功能仅在编辑已有题目时可用');
      return;
    }
    
    if (!isValidQuestion.value) {
      ElMessage.warning('请先完成题目基本内容再进行优化');
      return;
    }
    
    aiLoading.value = true;
    aiPrompt.value = '';
    
    // 构建优化提示
    const promptText = `请优化这道多选题，保持原有知识点不变，但使表述更加清晰、准确。难度调整为${getDifficultyText(questionForm.value.difficulty)}。`;
    
    aiMessages.value.push({ role: 'user', content: promptText });
    
    // 调用API优化题目
    const response = await optimizeQuestion(questionForm.value.questionId, prompt, questionForm.value.difficulty);
    
    console.log('AI优化题目响应:', response);
    
    if (response && response.data && response.data.content) {
      const content = response.data.content;
      
      aiMessages.value.push({ 
        role: 'assistant', 
        content: content.replace(/\n/g, '<br>') 
      });
      
      // 标记最后操作类型为优化
      aiLastAction.value = 'optimize';
      
      // 解析优化内容，但不自动应用
      if (response.data.questionContent && response.data.options) {
        const cleanOptions = response.data.options.map(opt => ({
          optionLabel: opt.optionLabel,
          optionContent: opt.optionContent
            .replace(/\n\n\n###$/, '')
            .replace(/\s*###.*$/gm, '')
            .replace(/\n{2,}/g, '\n')
            .replace(/\s*X\s*$/i, '') // 移除末尾可能的X标记
            .trim()
        }));
        
        // 处理多选题答案格式，确保是数组
        let answerArray = [];
        if (response.data.answer) {
          if (typeof response.data.answer === 'string') {
            answerArray = response.data.answer.split(',');
          } else if (Array.isArray(response.data.answer)) {
            answerArray = response.data.answer;
          }
        }
        
        // 构建结构化题目数据，但不自动应用
        aiGeneratedContent.value = {
          questionContent: response.data.questionContent,
          options: cleanOptions,
          answer: answerArray,
          analysis: response.data.analysis || ''
        };
      } else {
        // 后端未提供结构化数据，尝试前端解析
        const questionData = parseQuestionFromText(content);
        
        if (questionData && questionData.questionContent) {
          aiGeneratedContent.value = questionData;
        } else {
          aiGeneratedContent.value = {
            content: content,
            questionContent: '',
            options: [],
            answer: [],
            analysis: ''
          };
        }
      }
    }
  } catch (error) {
    console.error('AI优化题目出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，优化题目失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 分析当前题目
const analyzeCurrentQuestion = async () => {
  try {
    if (!isValidQuestion.value) {
      ElMessage.warning('请先完成题目基本内容再进行分析');
      return;
    }
    
    aiLoading.value = true;
    
    const questionData = {
      questionId: questionForm.value.questionId,
      questionType: 1, // 多选题
      questionContent: questionForm.value.questionContent,
      chapterId: questionForm.value.chapterId,
      difficulty: questionForm.value.difficulty,
      answer: questionForm.value.answer.join(','), // 多选题答案是数组，需要转成字符串
      options: questionForm.value.options,
      analysis: questionForm.value.analysis
    };
    
    // 构建分析提示并添加到消息列表
    const prompt = `请分析这道多选题的质量、难度和教学价值。`;
    aiMessages.value.push({ role: 'user', content: prompt });
    
    // 调用API分析题目
    const response = await analyzeGeneratedQuestion(questionData);
    
    console.log('AI分析题目响应:', response);
    
    if (response && response.data && response.data.content) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: response.data.content.replace(/\n/g, '<br>') 
      });
      
      // 标记为不可应用的内容
      aiLastAction.value = 'analyze';
      aiGeneratedContent.value = null;
    } else {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: '分析题目返回了无效数据，请重试。' 
      });
    }
  } catch (error) {
    console.error('AI分析题目出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，分析题目失败: ' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      renderAIMessageMath();
    });
  }
};

// 获取题目改进建议
const getImprovementSuggestion = async () => {
  try {
    if (!questionForm.value.questionId) {
      ElMessage.warning('只能为已保存的题目获取改进建议');
      return;
    }
    
    aiLoading.value = true;
    
    // 构建提示并添加到消息列表
    const prompt = `请分析这道多选题并提供改进建议`;
    aiMessages.value.push({ role: 'user', content: prompt });
    
    // 调用API获取建议
    const response = await generateQuestionSuggestion(questionForm.value.questionId);
    
    console.log('AI改进建议响应:', response);
    
    if (response && response.data && response.data.content) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: response.data.content.replace(/\n/g, '<br>') 
      });
      
      // 标记为不可应用的内容
      aiLastAction.value = 'suggestion';
      aiGeneratedContent.value = null;
    } else {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: '获取改进建议返回了无效数据，请重试。' 
      });
    }
  } catch (error) {
    console.error('AI获取改进建议出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，获取改进建议失败: ' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      renderAIMessageMath();
    });
  }
};

// 测试AI API
const testAIApi = async () => {
  try {
    aiLoading.value = true;
    aiMessages.value.push({ role: 'user', content: '测试AI API连接' });
    
    const response = await testAIConnection();
    
    if (response && response.data) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: '✅ AI API连接正常<br>返回数据: ' + JSON.stringify(response.data) 
      });
    } else {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: '❌ AI API连接失败：未返回有效数据' 
      });
    }
  } catch (error) {
    console.error('AI API测试失败:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '❌ AI API连接失败: ' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
    });
  }
};

// 初始化
onMounted(() => {
  getChapterTreeselect();
  
  // 检查路由路径判断是否为编辑模式
  const questionId = route.params.id;
  if (questionId) {
    isEdit.value = true;
    getDetail(questionId);
  }
  
  // 预加载MathJax
  loadMathJax(); 
});
</script>

<style>
.ql-editor {
  min-height: 200px;
}

.ql-toolbar {
  background-color: #f8f8f8;
}

.ql-container {
  font-size: 14px;
}

.content-html img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}

.preview-container img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
</style>

<style scoped>
.app-container {
  padding: 20px;
}

.content-box {
  min-height: 80px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #fff;
  cursor: pointer;
  transition: border-color 0.2s;
}

.content-box:hover {
  border-color: #409eff;
}

.placeholder-text {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.question-option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-label {
  width: 30px;
  text-align: center;
  font-weight: bold;
}

.option-content {
  flex: 1;
  margin: 0 10px;
  min-height: 40px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.button-group .el-button {
  margin: 0 10px;
}

.editor-container {
  width: 100%;
  margin-bottom: 20px;
}

.image-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}

.preview-container {
  padding: 15px;
}

.preview-title {
  font-weight: bold;
  margin-top: 15px;
  margin-bottom: 5px;
}

.preview-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-option {
  display: flex;
  margin: 10px 0;
}

.preview-option-content {
  margin-left: 10px;
}

.preview-answer {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  font-weight: bold;
}
.preview-container .MathJax {
  display: inline-block;
  vertical-align: middle;
}

/* 渲染后的公式样式 */
.preview-content, .preview-option-content {
  overflow: visible;
  word-wrap: break-word;
  word-break: break-word;
}

/* 添加额外的样式确保KaTeX备选方案也能正确显示 */
.katex { 
  font-size: 1.1em !important;
}

/* 确保MathJax公式正常显示 */
.preview-container .MathJax_Display {
  overflow: visible !important;
}

.preview-container .MJX_Assistive_MathML {
  display: none !important;
}

/* 避免公式溢出 */
.mjx-chtml {
  overflow: visible !important;
}
.ai-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  gap: 15px;
}

.ai-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.ai-empty-message {
  color: #909399;
  text-align: center;
  padding: 20px;
}

.ai-empty-message ul {
  text-align: left;
  margin: 10px auto;
  max-width: 300px;
}

.ai-empty-message li {
  margin: 8px 0;
  color: #606266;
}

.ai-messages {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ai-message {
  padding: 12px 15px;
  border-radius: 8px;
  max-width: 85%;
  white-space: pre-wrap;
  word-break: break-word;
}

.ai-message.user {
  align-self: flex-end;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  color: #409eff;
}

.ai-message.assistant {
  align-self: flex-start;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  color: #67c23a;
}

.ai-message-content {
  line-height: 1.5;
}

.ai-function-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 5px 0;
}

.ai-function-buttons .el-button {
  flex: 1;
  min-width: 120px;
}

.ai-input-area {
  position: relative;
}

.ai-input-tip {
  position: absolute;
  right: 10px;
  bottom: -20px;
  font-size: 12px;
  color: #909399;
}

.ai-action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 25px;
}

/* 数学公式渲染相关样式 */
.ai-message .MathJax {
  display: inline-block !important;
  margin: 0 0.2em;
  vertical-align: middle;
  max-width: 100%;
  overflow-x: auto;
}

.ai-message .katex {
  font-size: 1.1em !important;
  max-width: 100%;
  overflow-x: auto;
}

.ai-message mjx-container {
  overflow-x: auto !important;
  max-width: 100%;
}

/* 确保图片正确显示 */
.ai-message img {
  max-width: 100%;
  height: auto;
  object-fit: contain;
  margin: 5px 0;
}

/* 代码块样式 */
.ai-message pre {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.ai-message code {
  font-family: Monaco, Consolas, Courier New, monospace;
}

/* 加载状态样式 */
.ai-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

/* 滚动条样式 */
.ai-content::-webkit-scrollbar {
  width: 6px;
}

.ai-content::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.ai-content::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style>